package com.fpost.security;

import javax.servlet.http.HttpServletRequest;

import com.fpost.constants.CommonConstants;
import com.fpost.form.dto.UserDTO;
import com.fpost.manager.ArticleManager;

public class ActionSecurityUtils {
	
	public static UserDTO getUserDTO_fromSession(HttpServletRequest request) {
		return (UserDTO)request.getSession().getAttribute(CommonConstants.USER_DTO);
	}
	
	public static void putUserDTO_inSession(UserDTO userDTO, HttpServletRequest request) {
		request.getSession().setAttribute(CommonConstants.USER_DTO, userDTO);
	}
	
	public static boolean isAuthenticatedUser(long userId, HttpServletRequest request) throws Exception {
		UserDTO userDTO = getUserDTO_fromSession(request);
		if (userDTO != null && userDTO.getUserId() != null && userId == Long.parseLong(userDTO.getUserId())) {
			return true;
		} 
		return false;	
	}
	
	public static boolean isAuthor(long userId, long articleId) throws Exception {
		if (userId == new ArticleManager().getUserIdByArticleId(articleId)) {
				return true;
		}
		return false;
	}
	
	public static boolean isUpdateAllowed(long userId, long articleId) throws Exception {
		return isActionAllowed(userId, articleId);
	}

	public static boolean isDeleteAllowed(long userId, long articleId) throws Exception {
		return isActionAllowed(userId, articleId);
	}	
		
	// only author can delete or update his/her own articles
	private static boolean isActionAllowed(long userId, long articleId) throws Exception {		
		return isAuthor(userId, articleId);		
	}

}
